package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.Excel;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders) {
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("/userPage")
    public R pageOrder(int page, int pageSize) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        ordersService.page(pageInfo);
        long total = pageInfo.getTotal();
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> collect = records.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);

            LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
            qw.eq(OrderDetail::getOrderId, ordersDto.getNumber());
            List<OrderDetail> details = orderDetailService.list(qw);
            ordersDto.setOrderDetails(details);
            return ordersDto;
        }).collect(Collectors.toList());

        Map map = new HashMap();
        map.put("total", total);
        map.put("records", collect);
        return R.success(map);
    }

    @GetMapping("/page")
    public R page(int page, int pageSize, String number, String beginTime, String endTime) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(number),Orders::getId,number);
        qw.ge(StringUtils.isNotEmpty(beginTime),Orders::getOrderTime,beginTime);
        qw.le(StringUtils.isNotEmpty(endTime),Orders::getOrderTime,endTime);
        qw.orderByDesc(Orders::getCheckoutTime);
        ordersService.page(pageInfo, qw);
        List<Orders> records = pageInfo.getRecords();
        records.stream().map(item -> {
            item.setUserName(item.getUserName());
            return item;
        }).collect(Collectors.toList());
        return R.success(pageInfo);
    }

    @PutMapping
    public R status(@RequestBody Orders orders) {
        ordersService.updateById(orders);
        return R.success("订单正在派送");
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        //查询
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        List<Orders> list = ordersService.list(queryWrapper);
        //因为查询出来的集合对象和要返回的数据不一样，新建一个集合，类型是新建的实体类
        ArrayList<Excel> orderExcels = new ArrayList<>();
        //循环创建新的对象，并将创建好设好置的对象，加入新的集合中
        for (int i = 0; i < list.size(); i++) {
            Excel orderExcel = new Excel();
            orderExcel.setNumber(list.get(i).getId().toString());
            orderExcel.setStatus(list.get(i).getStatus());
            orderExcel.setUserName(list.get(i).getUserId().toString());
            orderExcel.setPhone(list.get(i).getPhone());
            orderExcel.setAddress(list.get(i).getAddress());
            orderExcel.setOrderTime(list.get(i).getOrderTime());
            orderExcel.setAmount(list.get(i).getAmount());
            orderExcels.add(orderExcel);
        }
        //设置浏览器下载的方式
        response.setContentType("application/x-download");
        //设置下载文件的名称及地址及UTF-8解决浏览器乱码问题
        response.addHeader("Content-Disposition", "attachment;filename=" + new String("订单明细表".getBytes("utf-8"), "ISO8859-1") + ".xlsx");
        //输出流
        OutputStream out = response.getOutputStream();
        //调用EasyExcel方法，通过out写出，excel表头是实体类，excel里面的表名是模板，写出新的集合
        EasyExcel.write(out,Excel.class).sheet("模板").doWrite(orderExcels);
        //释放资源
        out.flush();
        response.flushBuffer();
    }
}
